<template>
    <div class="material-ask-container">
        <!-- 工单信息标题 -->
        <div class="work-order-header">
            <h2 class="work-order-title">
                <el-icon>
                    <Document />
                </el-icon>
                备料单
                <!-- 显示关联的生产工单信息 -->
                <span v-if="relatedWorkOrder.produceName" class="related-work-order">
                    (关联工单: {{ relatedWorkOrder.produceName }})
                </span>
            </h2>
            <div class="work-order-status">
                <el-tag type="primary" size="large">待提交</el-tag>
                <el-button @click="Open()">当前订单</el-button>
            </div>
        </div>

        <!-- 工单表单内容 -->
        <el-card class="work-order-card" shadow="hover">
            <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="work-order-form">

                <!-- 第一行：物料申请单号 + 所需产品物料 -->
                <el-row :gutter="24" class="form-row">
                    <el-col :span="12">
                        <el-form-item label="物料申请单号" prop="materialAskCode">
                            <el-input v-model="ruleForm.materialAskCode" placeholder="系统自动生成" disabled :prefix-icon="Document" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="所需产品物料" prop="productMaterialsId">
                            <el-select v-model="ruleForm.productMaterialsId" placeholder="请选择所需产品物料" style="width: 100%"
                                :prefix-icon="Box">
                                <el-option v-for="item in cpwl" :key="item.id" :label="item.productMaterialsName"
                                    :value="item.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <!-- 第二行：物料申请数量 + 物料申请单位 -->
                <el-row :gutter="24" class="form-row">
                    <el-col :span="12">
                        <el-form-item label="物料申请数量" prop="materialAskCount">
                            <el-input-number v-model="ruleForm.materialAskCount" :min="0" :step="1000"
                                :step-strictly="false" controls-position="right" style="width: 100%"
                                placeholder="请输入物料申请数量">
                                <template #prefix>
                                    <el-icon>
                                        <Plus />
                                    </el-icon>
                                </template>
                            </el-input-number>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="物料申请单位" prop="materialAskUnit">
                            <el-input v-model="ruleForm.materialAskUnit" placeholder="请输入物料申请单位" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <!-- 第三行：物料申请描述（占满整行） -->
                <el-row class="form-row">
                    <el-col :span="24">
                        <el-form-item label="物料申请描述" prop="materialAskDesc">
                            <el-input v-model="ruleForm.materialAskDesc" type="textarea" :rows="4"
                                placeholder="请输入物料申请描述" show-word-limit maxlength="200" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <!-- 按钮区域 -->
                <el-row class="form-actions">
                    <el-col :span="24">
                        <el-form-item>
                            <div class="button-group">
                                <el-button type="primary" size="large" :icon="Check" @click="submitForm(ruleFormRef)">
                                    提交申请
                                </el-button>
                                <el-button size="large" :icon="Refresh" @click="resetForm(ruleFormRef)">
                                    重置表单
                                </el-button>
                            </div>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </el-card>
    </div>
    <el-dialog v-model="dialogVisible" title="当前物料申请工单信息" width="1200px">
        <el-table :data="tableData" border style="width: 100%">
            <el-table-column prop="materialAskCode" label="物料申请单号" width="120" />
            <el-table-column prop="productMaterialsName" label="所属产品物料名称" width="160" />
            <el-table-column prop="materialAskCount" label="物料申请数量" width="120" />
            <el-table-column prop="materialAskUnit" label="物料申请单位" width="120" />
            <el-table-column prop="materialAskDesc" label="物料申请描述" width="180" />
            <el-table-column prop="materialAskStatus" label="物料申请状态" width="110">
                <template #default="scope">
                    <el-tag type="warning" v-if="scope.row.materialAskStatus=='进行中'">进行中</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="150">
                <template #default="scope">
                    {{ moment(scope.row.createTime).format('YYYY-MM-DD') }}
                </template>
            </el-table-column>
            <el-table-column prop="createrPeople" label="申请人" width="120" />
            <el-table-column prop="updateTime" label="修改人" width="120" />
        </el-table>
          <!--分页-->
    <div class="pagination-container">
        <el-pagination v-model:current-page="page.PageIndex" v-model:page-size="page.PageSize"
            :page-sizes="[3, 6, 9, 12]" layout="total, sizes, prev, pager, next, jumper" :total="page.totalcount"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" class="custom-pagination" />
    </div>
    </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue';
import axios from 'axios';
import moment from 'moment';
import { ElMessage, ElMessageBox } from 'element-plus'
import { fr, pa } from 'element-plus/es/locales.mjs';
import type { FormInstance, FormRules } from 'element-plus'
import { useCounterStore } from '@/stores/counter'
import { useRoute } from 'vue-router'
import { Document, Edit, Box, Plus, Check, Refresh } from '@element-plus/icons-vue'
const pinia = useCounterStore();
const route = useRoute();

// 存储关联的生产工单信息
const relatedWorkOrder = reactive({
    produceName: '',
    produceCode: ''
});

// 生成物料申请单编号 - SQ加8位随机数
const generateMaterialAskCode = () => {
    // 生成8位随机数
    const randomNumber = Math.floor(10000000 + Math.random() * 90000000).toString();
    ruleForm.materialAskCode = 'SQ' + randomNumber;
}

onMounted(() => {
    GetProductMaterials()
    GetMaterialAsk()
    
    // 自动生成物料申请单编号
    generateMaterialAskCode()
    
    // 检查是否有从生产工单页面传来的参数
    if (route.query.produceName || route.query.produceCode) {
        // 如果有生产工单信息，则反填到物料申请描述中
        const produceName = route.query.produceName as string;
        const produceCode = route.query.produceCode as string;
        
        // 设置关联工单信息
        relatedWorkOrder.produceName = produceName || '';
        relatedWorkOrder.produceCode = produceCode || '';
        
        if (produceName) {
            ruleForm.materialAskDesc = `为生产工单"${produceName}"(编号:${produceCode})申请物料`;
        }
    }
})
const cpwl = ref([{ // 产品物料表格数据
    "id": null,
    "productMaterialsName": "",
}])
//产品物料向后端传参
const page1 = reactive({
    PageIndex: 1,
    PageSize: 100,
    totalcount: 0
})
//产品物料网络传输
const GetProductMaterials = () => {
    axios.get('/api/MaterialManagement/GetProductMaterials', { params: page1 }).then(res => {
        if (res.data.code == 200) {
            cpwl.value = res.data.totalPage
            page1.totalcount = res.data.totalcount
        }
    })
}

const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
    "materialAskCode": "",
    "productMaterialsId": null,
    "materialAskCount": 0, // 初始值为0，类型为数值
    "materialAskUnit": "",
    "materialAskDesc": "",
    "materialAskStatus": "进行中", // 与标签保持一致
    "createrPeople": pinia.piniaDto.accountName
})

const locationOptions = ['Home', 'Company', 'School']

const rules = reactive<FormRules>({
    materialAskCode: [
        { required: true, message: '请输入物料申请单号', trigger: 'blur' },
    ],
    productMaterialsId: [
        {
            required: true,
            message: '请选择所需产品物料',
            trigger: 'change',
        },
    ],
    materialAskCount: [
        {
            required: true,
            message: '请输入物料申请数量',
            trigger: 'change',
        },
        {
            type: 'number',
            min: 0,
            message: '数量必须大于等于0',
            trigger: 'change',
        }
    ],
    materialAskUnit: [
        {
            required: true,
            message: '请输入物料申请单位',
            trigger: 'change',
        },
    ],
    materialAskDesc: [
        {
            required: true,
            message: '请输入物料申请描述',
            trigger: 'change',
        },
    ],

})

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            axios.post('/api/MaterialManagement/AddMaterialAsk', ruleForm).then(res => {
                if (res.data.code == 200) {
                    ElMessage.success(res.data.message);
                } else {
                    ElMessage.error(res.data.error);
                }
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

const options = Array.from({ length: 10000 }).map((_, idx) => ({
    value: `${idx + 1}`,
    label: `${idx + 1}`,
}))
const dialogVisible = ref(false);
const Open = () => {
    dialogVisible.value = true;
}
const tableData = ref([])
//物料申请向后端传参
const page = reactive({
    PageIndex: 1,
    PageSize: 3,
    totalcount: 0
})
//物料群组网络传输
const GetMaterialAsk = () => {
    axios.get('/api/MaterialManagement/GetMaterialAsk', { params: page }).then(res => {
        if (res.data.code == 200) {
            tableData.value = res.data.totalPage
            page.totalcount = res.data.totalcount
        }
    })
}
const handleSizeChange = (val: number) => {
    console.log(`${val} items per page`)
    page.PageSize = val;
    GetMaterialAsk()
}
const handleCurrentChange = (val: number) => {
    console.log(`current page: ${val}`)
    page.PageIndex = val;
    GetMaterialAsk()
}
</script>

<style scoped>
/* 主容器样式 */
.material-ask-container {
    padding: 20px;
    background-color: #f5f7fa;
    min-height: calc(100vh - 40px);
}

/* 工单标题区域 */
.work-order-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    padding: 16px 24px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 12px;
    box-shadow: 0 4px 20px rgba(102, 126, 234, 0.3);
}

.work-order-title {
    display: flex;
    align-items: center;
    color: white;
    font-size: 24px;
    font-weight: 600;
    margin: 0;
}

.work-order-title .el-icon {
    margin-right: 12px;
    font-size: 28px;
}

.related-work-order {
    font-size: 16px;
    font-weight: 400;
    color: rgba(255, 255, 255, 0.9);
    margin-left: 12px;
    background: rgba(255, 255, 255, 0.1);
    padding: 4px 12px;
    border-radius: 6px;
    border: 1px solid rgba(255, 255, 255, 0.2);
}

.work-order-status {
    display: flex;
    align-items: center;
}

/* 工单卡片样式 */
.work-order-card {
    border-radius: 12px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
    border: 1px solid #e4e7ed;
    background: white;
}

.work-order-card:hover {
    box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
    transform: translateY(-2px);
    transition: all 0.3s ease;
}

/* 表单样式 */
.work-order-form {
    padding: 24px;
}

.form-row {
    margin-bottom: 24px;
}

.form-row:last-of-type {
    margin-bottom: 0;
}

/* 表单项样式优化 */
:deep(.el-form-item__label) {
    color: #303133;
    font-weight: 600;
    font-size: 14px;
    line-height: 1.6;
}

:deep(.el-input) {
    border-radius: 8px;
}

:deep(.el-input__wrapper) {
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    border: 1px solid #dcdfe6;
    transition: all 0.3s ease;
}

:deep(.el-input__wrapper:hover) {
    border-color: #c0c4cc;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

:deep(.el-input__wrapper.is-focus) {
    border-color: #409eff;
    box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

:deep(.el-select) {
    width: 100%;
}

:deep(.el-select .el-input__wrapper) {
    border-radius: 8px;
}

/* InputNumber组件样式 */
:deep(.el-input-number) {
    width: 100%;
}

:deep(.el-input-number .el-input__wrapper) {
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    border: 1px solid #dcdfe6;
    transition: all 0.3s ease;
}

:deep(.el-input-number .el-input__wrapper:hover) {
    border-color: #c0c4cc;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

:deep(.el-input-number .el-input__wrapper.is-focus) {
    border-color: #409eff;
    box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

:deep(.el-input-number__increase),
:deep(.el-input-number__decrease) {
    border-radius: 0;
    background-color: #f5f7fa;
    color: #606266;
    transition: all 0.3s;
}

:deep(.el-input-number__increase:hover),
:deep(.el-input-number__decrease:hover) {
    color: #409eff;
    background-color: #ecf5ff;
}

:deep(.el-input-number .el-input__inner) {
    text-align: left;
    padding-left: 40px;
}

:deep(.el-input-number .el-input__prefix) {
    left: 12px;
    color: #909399;
}

:deep(.el-textarea__inner) {
    border-radius: 8px;
    border: 1px solid #dcdfe6;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    transition: all 0.3s ease;
    resize: vertical;
}

:deep(.el-textarea__inner:hover) {
    border-color: #c0c4cc;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

:deep(.el-textarea__inner:focus) {
    border-color: #409eff;
    box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

/* 按钮区域样式 */
.form-actions {
    margin-top: 32px;
    padding-top: 24px;
    border-top: 2px solid #f0f2f5;
}

.button-group {
    display: flex;
    justify-content: center;
    gap: 16px;
}

.button-group .el-button {
    min-width: 120px;
    height: 44px;
    border-radius: 8px;
    font-weight: 600;
    font-size: 14px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
}

.button-group .el-button--primary {
    background: linear-gradient(135deg, #409eff 0%, #1890ff 100%);
    border: none;
}

.button-group .el-button--primary:hover {
    background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(64, 158, 255, 0.4);
}

.button-group .el-button:not(.el-button--primary) {
    background: white;
    border: 1px solid #d9d9d9;
    color: #666;
}

.button-group .el-button:not(.el-button--primary):hover {
    border-color: #409eff;
    color: #409eff;
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.15);
}

/* 响应式设计 */
@media (max-width: 768px) {
    .material-ask-container {
        padding: 16px;
    }

    .work-order-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 12px;
        padding: 16px;
    }

    .work-order-title {
        font-size: 20px;
    }

    .work-order-form {
        padding: 16px;
    }

    .form-row .el-col {
        margin-bottom: 16px;
    }

    .button-group {
        flex-direction: column;
        align-items: center;
    }

    .button-group .el-button {
        width: 100%;
        max-width: 200px;
    }
}

@media (max-width: 480px) {
    .work-order-header {
        margin-bottom: 16px;
        padding: 12px;
    }

    .work-order-title {
        font-size: 18px;
    }

    .work-order-title .el-icon {
        font-size: 24px;
        margin-right: 8px;
    }

    :deep(.el-form-item__label) {
        font-size: 13px;
    }
}

/* 动画效果 */
.work-order-card {
    animation: slideInUp 0.6s ease-out;
}

@keyframes slideInUp {
    from {
        opacity: 0;
        transform: translateY(30px);
    }

    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.work-order-header {
    animation: slideInDown 0.6s ease-out;
}

@keyframes slideInDown {
    from {
        opacity: 0;
        transform: translateY(-30px);
    }

    to {
        opacity: 1;
        transform: translateY(0);
    }
}
</style>
